<?php

namespace lh\controller;

use \GatewayWorker\Lib\Gateway;

class Game{
  //加入
  static function enter($cid,$name,$key,$hero,$now,$num,$owner){
    //task 如果gameList已经存在该ID
    
    //如果已经满人
    if(Gateway::getClientIdCountByGroup($key)==$num){
      $result=json_encode(['r'=>'/main/error','code' => 40,'msg' => '错误，房间已满']);
      Gateway::sendToClient($cid, $result);
      return;
    }

    //先返回玩家ID
    $result=json_encode(['r'=>'/game/cid','data'=>$cid]);
    Gateway::sendToClient($cid, $result);
    
    //key作为组id
    Gateway::joinGroup($cid,$key);

    //设置gameUser
    \LH::$gameUser[$cid]=['name'=>$name,'room'=>$key];

    //初始化gameList
    if(!isset(\LH::$gameList[$key])){
      \LH::$gameList[$key]=['num'=>$num,'now'=>0,'user'=>[],'owner'=>''];
    }

    //如果是房主
    if($owner){\LH::$gameList[$key]['owner']=$cid;}

    //加入gameList
    \LH::$gameList[$key]['user'][$cid]=['name'=>$name,'hero'=>$hero];
    \LH::$gameList[$key]['now']++;
    
    //如果人都到齐了
    if(Gateway::getClientIdCountByGroup($key)==$now){
      //通知游戏开始 返回资料
      $result=json_encode(['r'=>'/game/start','data'=>\LH::$gameList[$key]]);
      Gateway::sendToGroup($key,$result);
    }
  }

  //离开
  static function leave($cid){
    //离开游戏
    $roomid=\LH::$gameUser[$cid]['room'];
    unset(\LH::$gameList[$roomid]['user'][$cid]);
    unset(\LH::$gameUser[$cid]);
    \LH::$gameList[$roomid]['now']--;

    //如果游戏人数为0
    if(\LH::$gameList[$roomid]['now']==0){
      unset(\LH::$gameList[$roomid]);
      return;
    }

    //通知房间
    $result=json_encode(['r'=>'/game/leave','data'=>$cid]);
    Gateway::sendToGroup($roomid,$result);
  }

  //开始
  static function start($cid,$fleet){
    $roomid=\LH::$gameUser[$cid]['room'];
    $result=json_encode(['r'=>'/game/start/fleet','data'=>$fleet]);
    Gateway::sendToGroup($roomid,$result);
  }

  //聊天
  static function chat($cid,$content){
    $roomid=\LH::$gameUser[$cid]['room'];
    $data=['name'=>\LH::$gameUser[$cid]['name'],'content'=>$content];
    $result=json_encode(['r'=>'/game/chat','data'=>$data]);
    Gateway::sendToGroup($roomid,$result);
  }

  //行为请求
  static function actReq($cid,$type,$param){
    $roomid=\LH::$gameUser[$cid]['room'];
    $owner=\LH::$gameList[$roomid]['owner'];
    $data=['id'=>$cid,'type'=>$type,'param'=>$param];
    $result=json_encode(['r'=>'/game/act/req','data'=>$data]);
    Gateway::sendToClient($owner,$result);
  }
  
  //行为通知
  static function act($cid,$id,$type,$param){
    $roomid=\LH::$gameUser[$cid]['room'];
    $data=['id'=>$id,'type'=>$type,'param'=>$param];
    $result=json_encode(['r'=>'/game/act','data'=>$data]);
    Gateway::sendToGroup($roomid,$result);
  }

  //错误提示
  static function error($cid,$id,$content){
    $result=json_encode(['r'=>'/game/error','data'=>$content]);
    Gateway::sendToClient($id,$result);
  }
}